﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TopShelf_WindowsServce.Common
{
   public class LogHelper
    {
        /// <summary>
        /// 日志记录
        /// </summary>
        /// <param name="IP">IP地址</param>
        /// <param name="Context">内容</param>
        public static void WriteLine(string IP, string Context)
        {
            try
            {
                Console.WriteLine(Context);
                var now = DateTime.Now;
                var logContent = Context + "," + DateTime.Now.ToString() + "\r\n";
                var logFilePath = System.Windows.Forms.Application.StartupPath + @"\Log\" + DateTime.Now.ToString("yyyy-MM-dd") + @"\" + IP + ".txt";
                if (!System.IO.Directory.Exists(System.Windows.Forms.Application.StartupPath + @"\Log\" + DateTime.Now.ToString("yyyy-MM-dd") + @"\"))
                {
                    System.IO.Directory.CreateDirectory(System.Windows.Forms.Application.StartupPath + @"\Log\" + DateTime.Now.ToString("yyyy-MM-dd") + @"\");//不存在就创建文件夹
                }

                var logContentBytes = Encoding.Default.GetBytes(logContent);
                //由于设置了文件共享模式为允许随后写入，所以即使多个线程同时写入文件，也会等待之前的线程写入结束之后再执行，而不会出现错误
                using (FileStream logFile = new FileStream(logFilePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Write))
                {
                    logFile.Seek(0, SeekOrigin.End);
                    logFile.Write(logContentBytes, 0, logContentBytes.Length);
                }
            }
            catch (Exception ex)
            {
                //Console.WriteLine(ex.Message);
            }
        }
    }
}
